/**
 * 功能管理
 * @constructor
 */
function User() {
}

User.init = function () {
    let vm = new Vue({
        el: "#customModule",
        data: {
            //用户信息start
            userID: "",
            userName: "",
            realName: "",
            password: "",
            passwordConfirm: "",
            idCard: '',
            activity: "1",
            phone: "",
            createDateTime: "1",
            email: "1",
            userType: "",
            authCity: '',
            authDistrict: '',
            authTown: '',
            authType: '',
            deptId: '',
            deptName:'',
            //用户信息end
            //搜索
            UserNameCondition: "",
            userTypeCondition: "-1",
            activityCondition: "-1",
            cityCondition: -1,
            districtCondition: -1,
            townCondition: -1,
            cityConditionList: [],
            districtConditionList: [],
            townConditionList: [],
            //附加属性
            clickState: "",
            roleID: "",
            isAdd: "",
            roleList: [{id: 2, name: "执法管理人员"}],
            cityList: [],
            districtList: [],
            townList: [],
            city: true,
            district: true,
            town: true,
        },
        created() {
            this.roleID = $.cookie('RoleIds');
            document.getElementById("activityCondition")[0].selected = true;
            self = this;
            window.changeState = self.changeState;
            window.edit = self.edit;
            window.del = self.del;
            window.detail = self.detail;
            window.resetPwd = self.resetPwd
        },
        mounted() {
            this.initBootStrapSource();
            // this.initRole();
            this.getAuth();
            this.loadCities();
            this.initCity();
        },
        computed: {},
        watch: {
            cityCondition: function (city_id) {
                this.initDistrict(city_id);
            },
            districtCondition: function (district_id) {
                this.initTown(district_id);
            },
            authCity: function (city_id) {
                this.loadDistricts(city_id);
            },
            authDistrict: function (district_id) {
                this.loadTowns(district_id);
            }
        },
        methods: {
            /**
             * 初始化地市
             */
            initCity() {
                let url = "/city/getAllCity"
                axios.get(url).then(data => {
                    this.cityConditionList = data.data;
                })
            },
            /**
             * 初始化区县
             */
            initDistrict(city_id) {
                let url = "/district/getDistrictByCity?city_id=" + city_id;
                axios.get(url).then(data => {
                    this.districtConditionList = data.data;
                })
            },
            /**
             * 初始化乡镇
             */
            initTown(district_id) {
                let url = "/town/getTownByDistrict?district_id=" + district_id;
                axios.get(url).then(data => {
                    this.townConditionList = data.data;
                })
            },
            /**
             * 权限控制
             */
            getAuth() {
                let url = "/UserManage/getAuth";
                axios.post(url).then(data => {
                    if (data.data.code === "200") {
                        //判断用户权限
                        console.log('data.data.data', data.data.data);
                        if (data.data.data.authType == 1) { // 地市权限
                            this.cityCondition = data.data.data.authCity;
                            this.authCity = data.data.data.authCity;
                            this.district = false;
                            this.town = false;
                        } else if (data.data.data.authType == 2) { //区县权限
                            this.cityCondition = data.data.data.authCity;
                            this.districtCondition = data.data.data.authDistrict;
                            this.authCity = data.data.data.authCity;
                            this.authDistrict = data.data.data.authDistrict;
                            this.town = false;
                        } else if (data.data.data.authType == 3) { //乡镇权限
                            this.cityCondition = data.data.data.authCity;
                            this.districtCondition = data.data.data.authDistrict;
                            this.townCondition = data.data.data.authTown;
                            this.authCity = data.data.data.authCity;
                            this.authDistrict = data.data.data.authDistrict;
                            this.authTown = data.data.data.authTown;
                        }
                    }
                });
            },
            /**
             * 获取当前角色下，可供选择的角色
             */
            // initRole() {
            //     let url = "/RoleManage/initRole?roleID=" + $.cookie('RoleIds');
            //     axios.get(url).then(data => {
            //         if (data.data.code === "200") {
            //             this.roleList = [];
            //             for (let i = 0; i < data.data.data.length; i++) {
            //                 let result = data.data.data[i];
            //                 let param = {
            //                     id: result.roleID,
            //                     name: result.roleName
            //                 };
            //                 this.roleList.push(param);
            //             }
            //         }
            //     }).catch(e => {
            //
            //     })
            // },
            loadCities() {
                let that = this;
                $.ajax({
                    url: "/city/tableSearch",
                    type: "post",
                    data: JSON.stringify({pageSize: 100}),
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        that.cityList = data.data
                        // if (data.data[0]) {
                        //     // that.authCity = data.data[0].city_id
                        //     that.loadDistricts(data.data[0].city_id)
                        // }
                    }
                })
            },
            loadDistricts(cityId) {
                let that = this;
                $.ajax({
                    url: "/district/tableSearch",
                    type: "post",
                    data: JSON.stringify({city_id: cityId ? cityId : that.authCity, pageSize: 100}),
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        that.districtList = data.data
                        // if(data.data[0]){
                        //     that.loadTowns(data.data[0].district_id)
                        // }
                    }
                });
            },
            loadTowns(districtId) {
                let that = this;
                $.ajax({
                    url: "/town/tableSearch",
                    type: "post",
                    data: JSON.stringify({district_id: districtId ? districtId : that.authDistrict, pageSize: 100}),
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        that.townList = data.data
                    }
                });
            },
            initBootStrapSource() {
                $('#tableList').bootstrapTable({
                    url: '/UserManage/tableSearch',
                    method: 'post',
                    toolbar: "#toolbar",
                    sidePagination: 'server',
                    dataField: "data",
                    striped: true,
                    pagination: true,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    sortable: true,
                    sortName: 'createDateTime',
                    sortOrder: "desc",
                    search: false,
                    showRefresh: true,
                    showColumns: true,
                    showExport: true,
                    showToggle: true,
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        return {
                            pageSize: params.pageSize,      //页面大小
                            pageIndex: params.pageNumber,   //页码
                            sort: params.sortName,      //排序列名
                            sortOrder: params.sortOrder, //排位命令（desc，asc）
                            userName: $('#UserNameCondition').val(),
                            userType: $('#userTypeCondition').val(),
                            activity: $('#activityCondition').val(),
                            roleID: $.cookie('RoleIds'),
                            authCity: $("#cityCondition").val(),
                            authDistrict: $("#districtCondition").val(),
                            authTown: $("#townCondition").val(),
                        };
                    },
                    onLoadSuccess: function (data) {
                        //Help.alertSuccMessage("数据加载完毕");
                    },
                    onLoadError: function (status) {
                        // Help.alertErrorMessage("数据加载出错");
                    },
                    columns: [
                        {
                            title: '序号',//标题  可不加
                            align: "center",
                            width: 40,
                            sortable: true,
                            formatter: function (value, row, index) {
                                var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                                var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                                return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                            }
                        },
                        {field: 'userName', title: '用户名', align: 'center', sortable: true},
                        {field: 'realName', title: '姓名', align: 'center', sortable: true},
                        {field: 'dept_name', title: '部门', align: 'center', sortable: true},
                        {field: 'phone', title: '联系电话', align: 'center', sortable: true},
                        {field: 'email', title: '邮箱', align: 'center', visible: false},
                        {field: 'roleID', title: '角色编号', align: 'center', visible: false},
                        {field: 'roleName', title: '角色名称', align: 'center'},
                        {field: 'authRegion', title: '权限区域', align: 'center', sortable: true},
                        {field: 'createDateTime', title: '创建时间', align: 'center', sortable: true},
                        {
                            field: 'userType',
                            title: '用户类型',
                            align: 'center',
                            formatter(value, row, index) {
                                if (row.userType === 1) return '超级管理员';
                                else if (row.userType === 2) return '执法管理人员';
                                else if (row.userType === 3) return '养殖企业';
                                else if (row.userType === 4) return '屠宰企业';
                                else if (row.userType === 5) return '无害化处理企业';
                                else if (row.userType === 6) return '检疫人员';
                                else return '';
                            }
                        },
                        {
                            field: 'activity', title: '状态', align: 'center', sortable: true,
                            formatter: function (value, row, index) {
                                let optionHtml = "";
                                if (row.activity === 0) {
                                    optionHtml = "<span class=\"label label-danger custom\" title=\"停用\" >停用</span>";
                                } else if (row.activity === 1) {
                                    optionHtml = "<span class=\"label label-info\" title=\"启用\">启用</span>";
                                }
                                return optionHtml;

                            }
                        },
                        {
                            title: '操作', align: 'center',
                            formatter: function (value, row, index) {
                                let optionHtml;
                                for (let i = 0; i < row.buttonList.length; i++) {
                                    let button = row.buttonList[i];
                                    if (button.enDesc === "Select")
                                        optionHtml = " <a class=\"btn btn-info btn-xs\" href=\"javascript:void(0)\"  onclick='detail(" + JSON.stringify(row) + ")' title=\"详细\"><i class=\"fa fa-search\"></i>详细</a>";
                                    else if (button.enDesc === "Update")
                                        optionHtml = optionHtml + " <a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='edit(" + JSON.stringify(row) + ")'  title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                                    else if (button.enDesc === "Delete") {
                                        if (row.activity == 0) {
                                            optionHtml = optionHtml + " <a class=\"btn btn-success btn-xs\" href=\"javascript:void(0)\"  onclick='changeState(" + JSON.stringify(row) + ")'  title=\"启用\"><i class=\"fa fa-check-circle-o\"></i>启用</a>"
                                        } else {
                                            optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='changeState(" + JSON.stringify(row) + ")'  title=\"停用\"><i class=\"fa fa-ban\"></i>停用</a>"
                                        }
                                    } else vm.isAdd = button.enDesc === "Insert";
                                }
                                optionHtml = optionHtml + " <a class=\"btn btn-warning btn-xs\" href=\"javascript:void(0)\"  onclick='resetPwd(" + JSON.stringify(row) + ")'  title=\"重置密码\"><i class=\"fa fa-retweet\"></i>重置密码</a>"
                                return optionHtml;
                            }
                        }
                    ]
                });
            },
            /**
             * 查询
             */
            search() {
                vm.refresh();
            },
            /**
             * 重置
             */
            reset() {
                vm.UserNameCondition = "";
                $("#UserNameCondition").val("");
                $("#activityCondition").val("-1");
                vm.userTypeCondition = "";
                vm.activityCondition = "-1";
                $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
            },
            /**
             * 点击改变状态
             * @param data
             */
            changeState(data) {
                let url = "/UserManage/changeState";
                let pm = {
                    activity: data.activity === 1 ? 0 : 1,
                    userID: data.userID
                };
                axios.post(url, pm).then(data => {
                    if (data.data.code === "200") {
                        Help.alertInfoMessage("", "操作成功");
                        this.refresh();
                    }
                }).catch(e => {
                    console.log(e);
                    Help.alertErrorMessage("抱歉", "发生一点小错误")
                })
            },
            resetPwd(data) {
                $("#myform")[0].reset();
                vm.clickState = "resetPwd";
                vm.userID = data.userID;
                vm.userName = data.userName;
                vm.realName = data.realName;
                $('#userName').attr('readonly', 'readonly');
                $('#realName').attr('readonly', 'readonly');
                $('#passwordContainer').show();
                $('#nameContainer').show();
                $('#mailContainer').hide();
                $('#phoneContainer').hide();
                $('#preContainer').hide();
                $('#statusContainer').hide();
                $('#deptContainer').hide();
                $('#deptTreeContainer').hide();
                $("#save").removeAttr("disabled");
                $('#myModalAdd').modal('show')
            },
            /**
             * 编辑
             * @param data
             */
            edit(data) {
                vm.deptId = data.deptId;
                vm.deptName = data.dept_name;
                vm.userID = data.userID;
                vm.userName = data.userName;
                vm.activity = data.activity;
                vm.realName = data.realName;
                vm.phone = data.phone;
                vm.email = data.email;
                vm.userType = data.userType;
                vm.authCity = data.authCity;
                vm.authDistrict = data.authDistrict;
                vm.authTown = data.authTown;
                vm.authType = data.authType;
                vm.roleID = data.roleID;
                vm.idCard = data.idCard;
                vm.clickState = "edit";
                $('#userName').attr('readonly', 'readonly');
                $('#realName').removeAttr('readonly');
                $('#mailContainer').show();
                $('#phoneContainer').show();
                $('#preContainer').show();
                $('#statusContainer').show();
                $('#passwordContainer').hide();
                this.initTree();
                $('#myModalAdd').modal('show');
            },
            /**
             * 删除
             * @param data
             */
            del(data) {
                swal({
                    title: "确认是否删除",
                    text: "是否确认要删除该条记录？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    let url = "/UserManage/changeState";
                    let pm = {
                        activity: data.activity === 1 ? 0 : 1,
                        userID: data.userID
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("删除成功!", "请继续操作", "success");
                            vm.refresh();
                        } else {
                            swal("删除失败!", "请重试", "error");
                        }
                    }).catch(e => {
                        console.log(e);
                        Help.alertErrorMessage("抱歉", "发生一点小错误")
                    })
                });
            },
            /**
             * 详情
             */
            detail(data) {
                vm.clickState = "view";
                vm.deptId = data.deptId;
                vm.deptName = data.dept_name;
                vm.userName = data.userName;
                vm.activity = data.activity;
                vm.realName = data.realName;
                vm.idCard = data.idCard;
                vm.phone = data.phone;
                vm.email = data.email;
                vm.userType = data.userType;
                vm.authCity = data.authCity;
                vm.authDistrict = data.authDistrict;
                vm.authTown = data.authTown;
                vm.authType = data.authType;
                vm.roleID = data.roleID;
                vm.idCard = data.idCard;
                $('#mailContainer').show();
                $('#phoneContainer').show();
                $('#preContainer').show();
                $('#statusContainer').show();
                $('#passwordContainer').hide();
                this.initTree();
                $('#myModalAdd').modal('show');

            },
            /**
             * 新增
             */
            addRecord() {
                $('#userName').removeAttr('readonly');
                $('#realName').removeAttr('readonly');
                $('#mailContainer').show();
                $('#phoneContainer').show();
                $('#preContainer').show();
                $('#statusContainer').show();
                $('#passwordContainer').show();
                vm.userID = "";
                vm.userName = "";
                vm.realName = "";
                vm.password = "";
                vm.idCard = "";
                vm.passwordConfirm = "";
                vm.idCard = "";
                // vm.authCity = "0";
                // vm.authDistrict = "0";
                // vm.authTown = "0";
                vm.authType = "";
                vm.activity = "1";
                vm.phone = "";
                vm.email = "";
                vm.userType = "0";
                vm.clickState = 'add';
                $("#treeId").val("");
                $("#treeName").val("");
                this.initTree();
                $('#myModalAdd').modal('show');
                let url = "/UserManage/addInit";
                let pm = {
                    roleID: vm.roleID
                };
            },
            initTree() {
                var url = "/dept/treeData";
                var options = {
                    id: "tree",
                    treeId: "treeId",
                    url: url,
                    expandLevel: 2,
                    onClick: this.zOnClick
                };
                $.tree.init(options);
            },
            zOnClick(event, treeId, treeNode) {
                var treeId = treeNode.id;
                var treeName = treeNode.name;
                vm.deptId = treeId;
                vm.deptName = treeName;
            },
            /**
             * 保存
             */
            saveRecord() {
                if (!validateForm()) return false;
                if (vm.clickState === "edit") {
                    let url = "/UserManage/edit";
                    let pm = {
                        deptId: vm.deptId,
                        userID: vm.userID,
                        userName: vm.userName,
                        realName: vm.realName,
                        idCard: vm.idCard,
                        activity: vm.activity,
                        phone: vm.phone,
                        email: vm.email,
                        userType: vm.userType,
                        authCity: vm.authCity,
                        authDistrict: vm.authDistrict,
                        authTown: vm.authTown,
                        authType: vm.authType,
                        roleID: vm.roleID,
                        password: vm.password
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("保存成功!", '', "success");
                            $('#myModalAdd').modal('hide')
                            this.refresh();
                        } else {
                            swal("保存失败!", data.messages, "error");
                        }
                    }).catch(e => {
                        console.log(e);
                        Help.alertErrorMessage("抱歉", "发生一点小错误")
                    }).finally(() => {

                    })
                } else if (vm.clickState === "add") {
                    console.log("1321", vm.deptId);
                    let url = "/UserManage/add";
                    let pm = {
                        deptId: vm.deptId,
                        userID: vm.userID,
                        userName: vm.userName,
                        realName: vm.realName,
                        idCard: vm.idCard,
                        activity: vm.activity,
                        phone: vm.phone,
                        email: vm.email,
                        userType: vm.userType,
                        authCity: vm.authCity,
                        authDistrict: vm.authDistrict,
                        authTown: vm.authTown,
                        authType: vm.authType,
                        roleID: vm.roleID,
                        password: vm.password
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide')
                            swal("保存成功!", '如需修改，请至个人中心修改密码', "success");
                            this.refresh();
                        } else {
                            swal("保存失败!", data.data.message, "error");
                        }
                    }).catch(e => {
                        console.log(e);
                    }).finally(() => {

                    })
                } else if (vm.clickState === "resetPwd") {
                    let url = "/users/resetPwd";
                    let pm = {
                        userID: vm.userID,
                        password: vm.password
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide')
                            swal("操作成功!", "请继续操作", "success");
                        } else {
                            swal("操作失败!", data.message, "error");
                        }
                    }).catch(e => {
                        console.log(e);
                    }).finally(() => {

                    })
                }
            },
            refresh() {
                $('#tableList').bootstrapTable(('refresh'));
            }
        }
    });
};

jQuery.validator.addMethod("passwordValidator", function (value, element) {
    var pwd = $('#password').val();
    var pwdConfirm = $('#passwordConfirm').val();
    if (pwd != '' && pwdConfirm != '' && pwdConfirm != pwd) {
        return false;
    }
    return true;
}, "(登录密码与确认密码不一致)");


jQuery.validator.addMethod("isPhone", function (value, element) {
    var phone = $('#phone').val();
    if (phone != '') {
        var reg01 = /^(0|86|17951)?(13[0-9]|15[012356789]|17[01678]|18[0-9]|14[57])[0-9]{8}$/;
        var reg02 = /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        if (!reg01.test(phone) && !reg02.test(phone)) {
            return false
        }
    }
    return true;
}, "(请输入正确的联系方式)");

//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {
            userName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            realName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            phone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                isPhone: true
                // number: true, //必须是数字
            },
            idCard: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            password: {
                required: true,//必填
                minlength: 6, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            passwordConfirm: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: true
                // number: true, //必须是数字
            },
            authCity: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            roleID: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            }
        },
//错误信息提示
        messages: {
            userName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            realName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            phone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                isPhone: "(请输入正确的联系方式)"
                // number: true, //必须是数字
            },
            idCard: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            authCity: {
                required: "(必选)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            password: {
                required: "(必填)",
                minlength: "(至少六个字符)", //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            passwordConfirm: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: "(登录密码与确认密码不一致)"
                // number: true, //必须是数字
            },
            roleID: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                passwordValidator: "(登录密码与确认密码不一致)"
                // number: true, //必须是数字
            }
        },
    }).form();
}
